package estyle.auto.nkornilova.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

/**
 * Created with IntelliJ IDEA.
 * User: nkornilova
 * Date: 07.05.13
 * Time: 14:43
 * To change this template use File | Settings | File Templates.
 */
public class InsurerFilterPage extends AnyPage {

    public InsurerFilterPage(PageManager pages) {
        super(pages);
    }

    @FindBy(id = "regNum")
    private WebElement regNumField;

    @FindBy(id = "ogrn")
    private WebElement ogrnField;

    @FindBy(id = "inn")
    private WebElement innField;

    @FindBy(id = "kpp")
    private WebElement kppField;

    @FindBy(xpath = "//span[text()=\"Выбрать\"]/..")
    private WebElement submitButton;

    public InsurerFilterPage setRegNumField(String filterText) {
        regNumField.sendKeys(filterText);
        return this;
    }

    public InsurerFilterPage setKppField(String filterText) {
        kppField.sendKeys(filterText);
        return this;
    }

    public InsurerFilterPage setInnField(String filterText) {
        innField.sendKeys(filterText);
        return this;
    }

    public InsurerFilterPage setOgrnField(String filterText) {
        ogrnField.sendKeys(filterText);
        return this;
    }

    public InsurerFilterPage sendKeyEnterForSearch(String endFieldName)
    {
        if(endFieldName.equals("КПП"))
        {
            pressEnterIntoWebElement(kppField);
        }
        return this;
    }

    public InsurerFilterPage moveToInnerFrame()
    {
        moveToFrameByLocator(By.xpath("//iframe[@src='/fbsWeb/insurer/insurer_select.do']"));
        return this;
    }

    public InsurerFilterPage selectInsurerRecordOne() throws InterruptedException {

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

        List<WebElement> selectGridRecords = driver.findElements(By.xpath("//div[@class='datagrid-body']//tr//td[@field='regNum']"));
        if(selectGridRecords!=null && !selectGridRecords.isEmpty())
        {
            selectGridRecords.get(0).click();
        }
        return this;
    }

    public MessagePage clickOnChooseButton()
    {
        submitButton.click();
        return pages.messagePage;
    }

    public InsurerFilterPage moveToOut()
    {
        driver.switchTo().defaultContent();
        moveToFrameByLocator(By.xpath("//iframe[@id='appPopupFrame']"));
        return this;
    }
}
